package com.cyzy.controller;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyzy.dao.RoleMenu;
import com.cyzy.dao.UserRole;
import com.cyzy.dto.Result;
import com.cyzy.mapper.UserMapper;
import com.cyzy.pojo.Role;
import com.cyzy.pojo.User;
import com.cyzy.pojo.UserMenu;
import com.cyzy.service.EmailService;
import com.cyzy.service.MenuManageService;
import com.cyzy.service.RoleManageService;
import com.cyzy.service.UserService;
import com.cyzy.utils.CodeUtils;
import com.cyzy.utils.SHA256Utils;
import com.cyzy.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    CodeUtils codeUtils;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private TokenUtils tokenUtils;
    @Autowired
    private MenuManageService menuManageService;
    @Autowired
    private RoleManageService roleManageService;
    @Autowired
    private EmailService emailService;
    
    private Random random = new Random();
    @Autowired
    private UserMapper userMapper;


    @RequestMapping("/login")
    public Result login(@RequestParam String userAcc,
                        @RequestParam String userPwd,
                        @RequestParam String key,
                        @RequestParam String code) {
        System.out.println("账号" + userAcc + "密码" +  userPwd + "键" + key + "验证码" + code);
        // 1. 验证验证码
        String redisCode = redisTemplate.opsForValue().get(key);
        if (redisCode == null){
            return Result.error().code(400).message("验证码已过期");
        }
        if (!Objects.equals(redisCode, code)) {
            return Result.error().code(400).message("验证码错误");
        }

        // 2. 验证用户
        User user = userService.login(userAcc, SHA256Utils.encryptPassword(String.valueOf(userPwd)));
        if (user == null) {
            return Result.error().code(401).message("账号或密码错误");
        }

        // 3. 登录成功
        //生成token,并存入redis
        String token = tokenUtils.generateToken(user.getUserAcc());
        System.out.println(token);

        //用户ID存入redis,30分钟过期
        redisTemplate.opsForValue().set(token, String.valueOf(user.getUserId()),30, TimeUnit.MINUTES);

        return Result.ok().message("登录成功").data("token",token).data("user", user);
    }

    @RequestMapping("/getCode")
    public Result getCode(@RequestParam String key) {

        String codeBase64 = codeUtils.getRandomCodeImage();
        String code = codeUtils.getCode();

        //将验证码键值存入redis,5分钟过期
        redisTemplate.opsForValue().set(key, code,5, TimeUnit.MINUTES);

        System.out.println("验证码-----》 " + code);

        return Result.ok().data("codeBase64", codeBase64);
    }

    @RequestMapping("/forgotPassword")
    public Result forgotPassword(@RequestParam String userAcc,
                                 @RequestParam String userEmail,
                                 @RequestParam String key,
                                 @RequestParam String code) {
        System.out.println("账号" + userAcc + "邮箱" +  userEmail + "键" + key + "验证码" + code);
        // 1. 验证验证码

        String redisCode = redisTemplate.opsForValue().get(key);
        if (redisCode == null){
            return Result.error().code(400).message("验证码已过期");
        }
        if (!Objects.equals(redisCode, code)) {
            return Result.error().code(400).message("验证码错误");
        }

        // 2. 验证用户
        User user = userService.selectUserByUserAccAndUserEmail(userAcc, userEmail);
        if (user == null) {
            return Result.error().code(401).message("邮箱不匹配！");
        }
        // 3. 重置密码
        int min = 100000;
        int max = 999999;
        int userPwd = min + random.nextInt(max - min + 1);

        int result = userService.forgotPassword(userAcc, SHA256Utils.encryptPassword(String.valueOf(userPwd)));
        if (result < 1){
            return Result.error().code(401).message("密码重置失败！");
        }
        // 4.邮箱通知
        String subject = "教务系统账号密码重置通知";
        String text = "尊敬的用户：您好！您的密码已重置为：" + userPwd;

        emailService.sendSimpleEmail(userEmail, subject, text);
        return Result.ok();
    }


    @GetMapping("/selectAllUser")
    public Result selectAllUser(UserRole userRole, int pageSize, int pageNum){
        return Result.ok().data("user", userService.selectAllUser(userRole, pageSize, pageNum));
    }

    @GetMapping("/selectAllRole")
    public Result selectAllRole(Role role){
        List<Role> roleList = userService.selectAllRole(role);
        return Result.ok().data("roleList",roleList);
    }

    //菜单管理查询
    @GetMapping("/selectMenu")
    public Result selectAllMenu(UserMenu userMenu,int pageSize,int pageNum){
        Page<UserMenu> menu = menuManageService.selectMenu(userMenu,pageSize,pageNum);
        return Result.ok().data("menu",menu);
    }

    @GetMapping("/selectAllMenu")
    public Result selectAllMenu(UserMenu userMenu){
        List<UserMenu> menus = menuManageService.selectAllMenu(userMenu);
        return Result.ok().data("menus",menus);
    }

    @GetMapping("/getUser")
    public Result getUser(UserRole userRole){
        List<UserRole> getUser = userService.getUser(userRole);
        return Result.ok().data("getUser",getUser);
    }


    @DeleteMapping("/disabledUser/{id}")
    public Result disabledUser(@PathVariable Integer id){
        int i = userService.disabledUser(id);
        if(i == 0){
            return Result.error().message("禁用失败");
        }
        return Result.ok().message("封禁成功");
    }

   @PutMapping("/updateUser")
    public int updateUser(@RequestBody UserRole userRole){
        return userService.updateUser(userRole);
   }
    //管理员成员禁用启用
    @PutMapping("/updateUserStatus")
    public int updateUserStatus(@RequestBody UserRole userRole){
        return userService.updateUserStatus(userRole);
    }

    @PutMapping("/deleteUser/{id}")
    public int deleteUser(@PathVariable List<Integer> id){
        return userService.deleteUser(id);
    }

    @PutMapping("/deleteRole/{id}")
    public int deleteRole(@PathVariable List<Integer> id){
        return roleManageService.deleteRole(id);
    }

    //重置密码
    @PutMapping("/updateUserPwd")
    public int updateUserPwd(@RequestBody User user){
        return userService.updateUserPwd(user);
    }
    //角色菜单表
    @GetMapping("/selectRoleMenu")
    public Result selectRoleMenu(RoleMenu roleMenu, int pageSize, int pageNum){
        Page<RoleMenu> role = roleManageService.selectRoleMenu(roleMenu,pageSize,pageNum);
        return Result.ok().data("roleMenu",role);
    }

    @PostMapping("/addRoleMenu")
    public int addRoleMenu(@RequestBody RoleMenu roleMenu){
        return roleManageService.addRoleMenu(roleMenu);
    }

    @GetMapping("/getRoleMenu")
    public Result getRoleMenu(RoleMenu roleMenu){
        List<RoleMenu> getRoleMenu = roleManageService.getRoleMenu(roleMenu);
        return Result.ok().data("getRoleMenu",getRoleMenu);
    }

    @GetMapping("/getRole")
    public Result getRole(RoleMenu roleMenu){
        List<RoleMenu> getRole = roleManageService.getRole(roleMenu);
        return Result.ok().data("getRole",getRole);
    }

    @PostMapping("/addUser")
    public Result insertUser(@RequestBody UserRole userRole){
        UserRole exitUser = userService.exitUser(userRole);
        if (exitUser != null) {
           return Result.error().message("账号已存在");
        }else {
             userService.insertUser(userRole);
        }
        return Result.ok();
    }

    @PostMapping("/addUserRole")
    public int addUserRole(@RequestBody UserRole userRole){
        return userService.addUserRole(userRole);
    }

    @GetMapping("/getUserRole")
    public Result getUserRole(UserRole userRole){
        List<UserRole> getUserRole = userService.getUserRole(userRole);
        return Result.ok().data("getUserRole",getUserRole);
    }

    @PostMapping("/addRole")
    public Result insertRole(@RequestBody RoleMenu roleMenu){
        RoleMenu exitRole = roleManageService.exitRole(roleMenu);
        if (exitRole != null) {
            return Result.error().message("账号已存在");
        }else {
            roleManageService.insertRole(roleMenu);
            return Result.ok();
        }
    }
}
